package org.quickserver.net.client.monitoring.impl;

import java.io.IOException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.quickserver.net.client.BlockingUDPClient;
import org.quickserver.net.client.Host;
import org.quickserver.net.client.SocketBasedHost;
import org.quickserver.net.client.monitoring.HostMonitor;
















public class UDPMonitor
  implements HostMonitor
{
  private static final Logger logger = Logger.getLogger(UDPMonitor.class.getName());
  
  public char monitor(Host host) {
    char result = 'U';
    BlockingUDPClient udpClient = new BlockingUDPClient();
    try {
      SocketBasedHost udpHost = (SocketBasedHost)host;
      
      String hostName = udpHost.getInetSocketAddress().getHostName();
      int port = udpHost.getInetSocketAddress().getPort();




      
      String dataToSend = "test";
      if (udpHost.getRequestText() != null && !"".equals(udpHost.getRequestText().trim())) {
        dataToSend = udpHost.getRequestText();
      } else {
        logger.log(Level.SEVERE, "RequestText not configured for UDPHost{0}", hostName);
      } 
      
      String response = null;
      if (udpHost.getResponseTextToExpect() != null && 
        !"".equals(udpHost.getResponseTextToExpect().trim())) {
        
        response = new String(udpClient.sendAndReceiveBinary(hostName, port, dataToSend.getBytes()));
        if (response != null && response.contains(udpHost.getResponseTextToExpect())) {
          result = 'A';
        } else {
          logger.log(Level.FINE, "{0} Error: Text [{1}]Not found! Got: {2}", 
              new Object[] { udpHost, udpHost.getResponseTextToExpect(), response });
          result = 'D';
        } 
      } else {
        logger.log(Level.SEVERE, "ResponseTextToExpect not configured for UDPHost{0}", 
            hostName);
        result = 'U';
      } 
    } catch (IOException ioe) {
      logger.log(Level.SEVERE, "IOException", ioe);
      result = 'D';
    } catch (Throwable ex) {
      logger.log(Level.SEVERE, "Exception", ex);
      result = 'E';
    } finally {
      host.setLastCheckedOn(new Date());
      try {
        udpClient.close();
      } catch (IOException ex) {
        Logger.getLogger(UDPMonitor.class.getName()).log(Level.SEVERE, null, ex);
      } 
    } 
    return result;
  }
}
